package com.czh.www.thread;

import com.czh.www.domain.DataPacket;
import com.czh.www.domain.PacketQueue;
import com.czh.www.domain.SocketManage;
import com.czh.www.domain.SystemVar;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RecvPacketDaemon implements Runnable {
    public RecvPacketDaemon() {
    }

    public void run() {
        try {
            DatagramSocket ex = SocketManage.getInstance().getUdpSocket();
            DatagramPacket pack = new DatagramPacket(new byte[1500], 1500);

            while (true) {
                DataPacket dataPacket;
                do {
                    ex.receive(pack);
                    byte[] buffer = new byte[pack.getLength()];
                    System.arraycopy(pack.getData(), 0, buffer, 0, buffer.length);
                    dataPacket = DataPacket.createDataPacket(buffer, pack.getAddress().getHostAddress());
                } while (dataPacket == null);

                SystemVar.PACKET_QUEUE_EMPTY.acquire();
                PacketQueue.pushPacket(dataPacket);
                SystemVar.PACKET_QUEUE_FULL.release();
            }
        } catch (SocketException var5) {
            var5.printStackTrace();
            System.exit(0);
        } catch (IOException var6) {
            var6.printStackTrace();
        } catch (InterruptedException var7) {
            Logger.getLogger(RecvPacketDaemon.class.getName()).log(Level.SEVERE, (String) null, var7);
        }

    }
}
